const socket = new WebSocket('ws://localhost:8080/chat');

socket.onopen = function () {
    console.log('WebSocket 连接已建立');
};

socket.onmessage = function (event) {
    console.log('收到消息:', event.data);
    const messagesDiv = document.getElementById('messages');
    if (messagesDiv) {
        const messageElement = document.createElement('div');
        messageElement.textContent = event.data;
        messagesDiv.appendChild(messageElement);
        messagesDiv.scrollTop = messagesDiv.scrollHeight;
    } else {
        console.error('未找到消息显示区域');
    }
};

socket.onclose = function () {
    console.log('WebSocket 连接已关闭');
};

socket.onerror = function (error) {
    console.error('WebSocket 错误:', error);
};

function sendMessage() {
    const messageInput = document.getElementById('messageInput');
    if (messageInput) {
        const message = messageInput.value.trim();
        if (message) {
            console.log('发送消息:', message);
            socket.send(message);
            messageInput.value = '';
        }
    } else {
        console.error('未找到消息输入框');
    }
}